﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using OpenIddict.EntityFrameworkCore.Models;

namespace SageKing.OpenIddict.UI.Infrastructure.Data;


public class AppDbContext : IdentityDbContext<AppUser, AppRole, long>
{
    private string _tenantId; // 从当前请求注入

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<AppUser>().ToTable("Users"); // 修改用户表名
        builder.Entity<AppUser>().Property(u => u.Email).HasMaxLength(200); // 扩展字段长度

        builder.Entity<AppUser>(b =>
        {
            b.Property<string>("TenantId");
            b.HasIndex("TenantId");
        });

        builder.Entity<AppRole>().ToTable("Roles");
        builder.Entity<AppRole>(b =>
        {
            b.Property<string>("TenantId");
            b.HasIndex("TenantId");
        });

        builder.Entity<IdentityUserRole<long>>().ToTable("UserRoles");
        builder.Entity<IdentityUserClaim<long>>().ToTable("UserClaims");
        builder.Entity<IdentityUserLogin<long>>().ToTable("UserLogins");
        builder.Entity<IdentityUserToken<long>>().ToTable("UserTokens");
        builder.Entity<IdentityRoleClaim<long>>().ToTable("RoleClaims");

        // 正确：在实体上定义过滤器
        builder.Entity<AppUser>().HasQueryFilter(u => u.TenantId == _tenantId);
        builder.Entity<AppRole>().HasQueryFilter(r => r.TenantId == _tenantId);
    }

    public void SetTenantId(string tenantId) => _tenantId = tenantId;

    public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries<ITenantEntity>())
        {
            if (entry.State == EntityState.Added)
                entry.Entity.TenantId = _tenantId; // 自动注入新增数据
        }
        return base.SaveChanges();
    }
}